package test;

import java.util.Scanner;

// 自定义异常类，用于处理取款金额超出账户余额的情况
class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) {
        super(message);
    }
}

public class ATM {
    private double balance; // 账户余额
    private Scanner scanner; // 用于读取用户输入

    public ATM(double initialBalance) {
        this.balance = initialBalance;
        this.scanner = new Scanner(System.in);
    }

    // 查询余额
    public void checkBalance() {
        System.out.printf("当前余额为: %.2f\n", balance);
    }

    // 取款
    public void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException("金额不足，无法取款。");
        }
        balance -= amount;
        System.out.printf("成功取出: %.2f，剩余余额: %.2f\n", amount, balance);
    }

    // 存款
    public void deposit(double amount) {
        balance += amount;
        System.out.printf("成功存入: %.2f，当前余额: %.2f\n", amount, balance);
    }

    // 显示菜单并处理用户选择
    public void showMenu() {
        int choice;
        do {
            System.out.println("请选择操作：");
            System.out.println("1. 查询余额");
            System.out.println("2. 取款");
            System.out.println("3. 存款");
            System.out.println("4. 退出");
            System.out.print("请输入选项（1-4）：");

            choice = scanner.nextInt();

            switch (choice) {
                case 1 -> checkBalance();
                case 2 -> {
                    System.out.print("请输入取款金额：");
                    double withdrawAmount = scanner.nextDouble();
                    try {
                        withdraw(withdrawAmount);
                    } catch (InsufficientFundsException e) {
                        System.out.println(e.getMessage());
                    }
                }
                case 3 -> {
                    System.out.print("请输入存款金额：");
                    double depositAmount = scanner.nextDouble();
                    deposit(depositAmount);
                }
                case 4 -> System.out.println("退出系统。");
                default -> System.out.println("无效选项，请重新输入。");
            }
        } while (choice != 4);
    }

    public static void main(String[] args) {
        ATM atm = new ATM(1000.0); // 假设初始余额为1000元
        atm.showMenu();
    }
}
